// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const {type, user, title, content, page, size, _id} = event;
  const db = cloud.database()
  const activity = db.collection('activity');
  const userDB = db.collection('user');
  if (!user) {
    return {code: 403, message: '没有权限，请重新登录'}
  }
  const userData = await userDB.where({nickName: user}).get();
  const user_id = userData?.data?.[0]?._id;

  if (!user_id) {
    return {code: 403, message: '没有权限，请重新登录'}
  }
  if (type === 'get') {
    const {data} = await activity.where({creator_id: user_id}).get();
    return {items: data.reverse().slice((page - 1)*size, page * size), total: data.length}
  }

  if (type === 'post') {
    const res = await activity.add({data: {
      title, content, creator_id: user_id,
      time: new Date()
    }});
    return {message: '新增成功', data: res}
  }

  if (type === 'put') {
    console.log('update ....', _id);
    console.log('data item', activity.doc(_id));
    const data = await activity.doc(_id).update({
      data: {title, content, time: new Date()}
    });
    return  {message: '编辑成功', data}
  }

  if (type === 'delete') {
    const data = await activity.doc(_id).remove();
    return {message: '删除成功'}
  }
}